package com.example.tys.baseapplication.util;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.Build;

import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStream;

/**
 * Created by tys on 2018/1/19.
 */

public class BitmapUtil {


    /**
     * bitmap文件压缩
     *
     * @param format
     * @param quality  质量（0-100）0尺寸最小， 100质量最高
     * @param destFile 压缩后输出
     */
    public static boolean bitmapCompress(Bitmap bitmap, Bitmap.CompressFormat format, int quality, File destFile) throws IOException {
        if (destFile.exists() && destFile.isDirectory()) {
            throw new IOException("Destination '" + destFile + "' exists but is a directory");
        }
        try (OutputStream stream = new FileOutputStream(destFile)) {
            return bitmap.compress(format, quality, stream);
        }
    }

    /***
     * bitmap缩放
     * @param context
     * @param resId
     * @param outMaxWidth
     * @param outMaxHeight
     * @param outConfig
     * @param reusable 内存复用的bitmap, {@link #isReusedBitmap}
     * @return
     */
    public static Bitmap bitmapReSize(Context context, int resId, int outMaxWidth, int outMaxHeight, Bitmap.Config outConfig, Bitmap reusable) {
        BitmapFactory.Options opts = new BitmapFactory.Options();
        opts.inJustDecodeBounds = true;
        BitmapFactory.decodeResource(context.getResources(), resId, opts);//decodeFile()
        int width = opts.outWidth;
        int height = opts.outHeight;
        opts.inSampleSize = calculateSampleSize(width, height, outMaxWidth, outMaxHeight);
        opts.inPreferredConfig = outConfig;
        opts.inJustDecodeBounds = false;
        //需要设置为异变的才能够被复用内存
        opts.inMutable = true;
        //内存复用的bitmap
        if (reusable != null)
            opts.inBitmap = reusable;
        return BitmapFactory.decodeResource(context.getResources(), resId, opts);
    }

    /**
     * 检查指定的bitmap是否可用内存复用
     *
     * @param reusedBitmap
     * @param outWidth
     * @param outHeight
     * @param outInSampleSize
     * @param outConfig
     * @return
     */
    public static boolean isReusedBitmap(Bitmap reusedBitmap, int outWidth, int outHeight, int outInSampleSize, Bitmap.Config outConfig) {
        if (!reusedBitmap.isMutable()) //可被复用的Bitmap必须设置inMutable为true；
            return false;
        if (Build.VERSION.SDK_INT > Build.VERSION_CODES.KITKAT) {
            int bytes = outConfig == Bitmap.Config.ARGB_8888 ? 4 : 2;
            //如果缩放系数大于1 获得缩放后的宽与高
            if (outInSampleSize > 1) {//Android4.4(API 19)之后被复用的Bitmap的内存 必须大于等于需要申请内存的Bitmap的内存
                outWidth /= outInSampleSize;
                outHeight /= outInSampleSize;
            }
            return reusedBitmap.getAllocationByteCount() >= outHeight * outWidth * bytes;
        } else {
            //Android4.4(API 19)之前，只有格式为jpg、png，同等宽高（要求苛刻），inSampleSize为1的Bitmap才可以复用
            return outWidth == reusedBitmap.getWidth() &&
                    outHeight == reusedBitmap.getHeight() &&
                    outInSampleSize == 1;
        }
    }


    /**
     * 计算bitmap的缩放系数
     *
     * @param srcWidth
     * @param srcHeight
     * @param detMaxWidth
     * @param derMaxHeight
     * @return
     */
    public static int calculateSampleSize(int srcWidth, int srcHeight, int detMaxWidth, int derMaxHeight) {
        int sampleSize = 1;
        if (srcWidth > detMaxWidth && srcHeight > derMaxHeight) {
            for (sampleSize = 2; srcWidth / sampleSize > detMaxWidth && srcHeight / sampleSize > derMaxHeight; ) {
                sampleSize *= 2;
            }
        }
        return sampleSize;
    }


}
